package com.module.overview.ui.duringExercise

import android.animation.Animator
import android.annotation.SuppressLint
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.helper.RouterHelper
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.app.utls.TimerUtils
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.listener.AlertDialogConfirmBtnListener
import com.common.base.utils.AppUtils
import com.common.base.utils.LogUtils
import com.common.base.utils.MathUtil.printNoMoreZero
import com.common.base.utils.StatusBarUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.hDu.SportMonitorTask
import com.module.ble.listener.CusSportMonitorDataExpandListener
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AizoSDKUtil.getCusSportLiveData
import com.module.ble.utils.AizoSDKUtil.setCusSportStop
import com.module.ble.utils.DeviceFirmType
import com.module.fitness.utils.ExerciseType
import com.module.fitness.utils.getEnumToExType
import com.module.fitness.utils.getExTypeToEnum
import com.module.overview.R
import com.module.overview.databinding.OverviewActivityDuringExerciseBinding

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/4/7
 * <p>
 * 描述：运动中页面
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_OVERVIEW_DURING_EXERCISE)
class DuringExerciseActivity :
    AppActivity<OverviewActivityDuringExerciseBinding, DuringExerciseViewModel>(),
    View.OnClickListener, CusSportMonitorDataExpandListener {
    val TAG: String = DuringExerciseActivity::class.java.simpleName

    override fun getViewModel(): Class<DuringExerciseViewModel> =
        DuringExerciseViewModel::class.java

    override fun getViewContentBinding() =
        OverviewActivityDuringExerciseBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var mType: ExerciseType? = ExerciseType.RUNNING_IN

    @Autowired(name = KeyBundle.EXPAND_DATA)
    @JvmField
    var curSportId: Long = -1

    @Autowired(name = KeyBundle.TIME_DURATION_KEY)
    @JvmField
    var timeDuration: Long = 0

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        mViewContentBinding.tvTopTitle.text = when (mType) {
            ExerciseType.RUNNING_IN -> resources.getString(R.string.overview_indoor_running)
            ExerciseType.RUNNING_OUT -> resources.getString(R.string.overview_outdoor_running)
            ExerciseType.FITNESS_IN -> resources.getString(R.string.overview_indoor_bodybuilding)
            ExerciseType.FITNESS_OUT -> resources.getString(R.string.overview_outdoor_bodybuilding)
            ExerciseType.CYCLING_IN -> resources.getString(R.string.overview_indoor_cycling)
            ExerciseType.CYCLING_OUT -> resources.getString(R.string.overview_outdoor_cycling)
            else -> resources.getString(R.string.ac_during_exercise_title)
        }

        AizoSDKUtil.getBleBindingMac()?.let {
            AizoSDKUtil.connectBleDevice(it,AizoSDKUtil.getRingFirm())
            mViewContentBinding.tvRingInfoLL.connectStateUi(1)
        }

        Log.e("DuringExerciseActivity", "SSSSSS: DuringExerciseActivity-initViews")

    }

    override fun initEvents() {
        super.initEvents()

        AizoSDKUtil.addSportMonitorDataExpandListener(this)

        mViewContentBinding.imgBack.setOnClickListener(onClick = this)
        mViewContentBinding.imgRun.setOnClickListener(onClick = this)
        mViewContentBinding.imgLock.setOnClickListener(onClick = this)

        mViewContentBinding.imgPause.setOnClickListener(onClick = this)
        mViewContentBinding.imgContinue.setOnClickListener(onClick = this)

        addImgCloseLongClickListener()
        addImgUnLockLongClickListener()

        mViewModel.timeString.observe(this) {
            mViewContentBinding.tvTakeTime.text = it
        }

        LiveEventBus.get(KeyEvents.KEY_TIME_EVENT).observe(this) {
            val value = TimerUtils.getTimerStep(KeyEvents.KEY_TIME_EVENT_DURING_EX)
            if (value != -1 && value % 2 == 0) {//断连时每2秒执行一次查询 && isActivityVisible
                getCusSportLiveData(getEnumToExType(mType!!), curSportId) { km, hr, kcal, realStep ->
                    mViewContentBinding.tvKilocalorie.text = printNoMoreZero(kcal)
                    (hr >=1).yes { mViewContentBinding.tvHr.text = hr.toString() }
                }
            }
        }

        mViewContentBinding.animCountdown.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(p0: Animator) {
                Log.e("$TAG---SOU---LottieAnimationView", "onAnimationStart:")
            }

            override fun onAnimationEnd(p0: Animator) {
                Log.e("$TAG---SOU---LottieAnimationView", "onAnimationEnd:")
                startSport()
                changeRunBtnUI(false)
                setVisibility(mViewContentBinding.animCountdown, false)
            }

            override fun onAnimationCancel(p0: Animator) {
                Log.e("$TAG---SOU---LottieAnimationView", "onAnimationCancel:")
            }

            override fun onAnimationRepeat(p0: Animator) {
                Log.e("$TAG---SOU---LottieAnimationView", "onAnimationRepeat:")
            }

        })
        mViewContentBinding.animCountdown.addAnimatorPauseListener(object :
            Animator.AnimatorPauseListener {
            override fun onAnimationPause(p0: Animator) {
                Log.e("$TAG---SOU---LottieAnimationView", "onAnimationPause:")
            }

            override fun onAnimationResume(p0: Animator) {
                Log.e("$TAG---SOU---LottieAnimationView", "onAnimationResume:")
            }

        })
    }

    override fun lazyInitData() {
        super.lazyInitData()
        Log.e(TAG, "SSSSSS: DuringExerciseActivity-lazyInitData")
    }

    override fun onDestroy() {
        AizoSDKUtil.mHduSportMonitorTask = null
        AizoSDKUtil.removeSportMonitorDataExpandListener(this)
        super.onDestroy()
        TimerUtils.removeTimer(KeyEvents.KEY_TIME_EVENT_DURING_EX)
        mViewModel.timerJob?.cancel()
    }

    override fun onClick(v: View?) {
        if (mType == null) {
            showToast(getString(R.string.overview_abnormal_movement_pattern_hint))
            return
        }
        when (v) {
            mViewContentBinding.imgBack -> finish()
            mViewContentBinding.imgRun -> {

                if (!AizoSDKUtil.isConnect()) {
                    showToast(getString(R.string.ble_device_disconnect))
                    return
                }
                showDialogLoading()//getEnumToExType(subType), TimeUtils.getTimeDateLong()
                AizoSDKUtil.checkSportStatus { sportStatus, lastSportId, lastSportType ->
                    dismissLoadingDialog()
                    Log.e(
                        "$TAG-checkSportStatus",
                        "YQ: SSSSSS: sportStatus: ${sportStatus}-------lastSportId:${lastSportId}-------lastSportType:${lastSportId}"
                    )
                    when (sportStatus) {
                        1, 2 -> {//1,2 : 有正在进行的运动，需要调用ServiceSdkCommandV2.sportStopAndGetRecord方法停止成功后回调运动综合数据

//                            showAlertDialogTwoBtn(//可恢复并继续运动业务逻辑
//                                AppUtils.getString(com.module.ble.R.string.cancel_btn_zh2),
//                                AppUtils.getString(com.module.ble.R.string.ok_btn_zh),
//                                "提示",
//                                "有正在进行的运动，先结束当前运动",
//                                message2="",
//                                true,
//                                object : AlertDialogConfirmBtnListener {
//                                    override fun onCancelBtnClick() {
//                                        AizoSDKUtil.getYQSportStopAndGetRecord(
//                                            sportId = lastSportId,
//                                            sportType = lastSportType,
//                                            onResult = { success ->
//                                                dismissLoadingDialog()
//                                                success.yes {
//                                                    playAnimationAndUi()
//                                                }
//                                            },
//                                            onSportRecord = { record ->
//                                                // 处理运动记录数据
//                                                record?.let {
//
//                                                    curSportId = lastSportId
//                                                    mType = getExTypeToEnum(lastSportType)
//                                                    timeDuration = getTimeDateLong() - lastSportId
//
//                                                    mViewModel.seconds = timeDuration / 1000//毫秒转秒，对应ViewModel的seconds单位
////                                        (timeDuration>=1).yes {mViewModel.updateTimerText(mViewModel.seconds) }
//                                                    mViewModel.resumeTimer()
//
//                                                    AizoSDKUtil.isConnect().yes {
//                                                        mType?.let {
//                                                            AizoSDKUtil.setSportStart(
//                                                                getEnumToExType(it),
//                                                                curSportId
//                                                            )
//                                                        }
//                                                    }.otherwise {
//                                                        showToast(getString(R.string.ble_device_disconnect))
//                                                    }
//                                                    changeRunBtnUI(false)
//                                                    setVisibility(mViewContentBinding.animCountdown, false)
//                                                }
//                                            }
//                                        )
//
//                                    }
//
//                                    override fun onConfirmBtnClick() {
//                                        // 确定按钮的回调逻辑
//                                        //有正在进行的运动，需要先停止当前运动然后获取运动综合数据
//                                        showDialogLoading()
//                                        AizoSDKUtil.getYQSportStopAndGetRecord(
//                                            lastSportId,
//                                            lastSportType
//                                        ) { sportStopIt ->
//                                            dismissLoadingDialog()
//                                            sportStopIt.yes {
//                                                playAnimationAndUi()
//                                            }
//                                        }
//                                    }
//                                })

                            showAlertDialogOneBtn(
                                AppUtils.getString(com.module.ble.R.string.ok_btn_zh),
                                "提示",
                                "有正在进行的运动，先结束当前运动",
                                true,
                                object : AlertDialogConfirmBtnListener {
                                    override fun onCancelBtnClick() {
                                        curSportId = lastSportId
//                                        mType = getExTypeToEnum(lastSportType)
//                                        timeDuration = getTimeDateLong() - lastSportId
//
//                                        mViewModel.seconds = timeDuration / 1000//毫秒转秒，对应ViewModel的seconds单位
////                                        (timeDuration>=1).yes {mViewModel.updateTimerText(mViewModel.seconds) }
//                                        mViewModel.resumeTimer()
//                                        changeRunBtnUI(false)
//                                        changeCloseBtnUI(false)
//                                        changePauseBtnUI(true)
//                                        dismissLoadingDialog()
                                    }

                                    override fun onConfirmBtnClick() {
                                        // 确定按钮的回调逻辑
                                        //有正在进行的运动，需要先停止当前运动然后获取运动综合数据
                                        showDialogLoading()
                                        AizoSDKUtil.getYQSportStopAndGetRecord(
                                            sportId = lastSportId,
                                            sportType = lastSportType,
                                            onResult = { success ->
                                                dismissLoadingDialog()
                                                success.yes {
                                                    playAnimationAndUi()
                                                }
                                            },
                                            onSportRecord = { record ->
                                            }
                                        )
                                    }
                                })
                        }

                        3 -> {
                            //有运动数据需要上传，先获取运动数据
                            AizoSDKUtil.getYQSportRecord {
                                playAnimationAndUi()
                            }
                        }

                        else -> {
                            (getEnumToExType(mType!!) > 0).yes {
                                //无正在进行的运动，立即开始运动
                                playAnimationAndUi()
                            }
                        }
                    }
                }
            }

            mViewContentBinding.imgPause -> {
                AizoSDKUtil.isConnect().yes {
                    showDialogLoading()
                    AizoSDKUtil.setCusSportPause(getEnumToExType(mType!!), curSportId)
                }.otherwise {
                    showToast(getString(R.string.ble_device_disconnect))
                }
            }

            mViewContentBinding.imgContinue -> {
                AizoSDKUtil.isConnect().yes {
                    showDialogLoading()
                    AizoSDKUtil.setCusSportResume(getEnumToExType(mType!!), curSportId)
                }.otherwise {
                    showToast(getString(R.string.ble_device_disconnect))
                }
            }

            mViewContentBinding.imgLock->{
                changePauseBtnUI(false)
                changeUnLockBtnUI(true)
            }
        }
    }

    fun playAnimationAndUi() {
        setVisibility(mViewContentBinding.animCountdown, true)
        mViewContentBinding.animCountdown.progress = 0f
        mViewContentBinding.animCountdown.playAnimation()
    }


    fun startSport() {
        AizoSDKUtil.isConnect().yes {
            mType?.let {
                AizoSDKUtil.setSportStart(
                    getEnumToExType(it),
                    TimeUtils.removeMilliseconds(TimeUtils.getTimeDateLong())
                )
            }
        }.otherwise {
            showToast(getString(R.string.ble_device_disconnect))
        }
    }

    fun changeRunBtnUI(isVisible: Boolean) {
        setVisibility(mViewContentBinding.imgRun, isVisible)
        setVisibility(mViewContentBinding.imgBack, isVisible)
    }

    fun changePauseBtnUI(isVisible: Boolean) {
        setVisibility(mViewContentBinding.imgPause, isVisible)
        setVisibility(mViewContentBinding.imgLock, isVisible)
    }

    fun changeCloseBtnUI(isVisible: Boolean) {
        setVisibility(mViewContentBinding.imgContinue, isVisible)
        setVisibility(mViewContentBinding.imgClose, isVisible)
        setVisibility(mViewContentBinding.tvCloseHint, isVisible)
        setVisibility(mViewContentBinding.tvAutoEndHint, isVisible)
    }

    fun changeUnLockBtnUI(isVisible: Boolean) {
        setVisibility(mViewContentBinding.imgUnLockBg, isVisible)
        setVisibility(mViewContentBinding.imgUnLock, isVisible)
        setVisibility(mViewContentBinding.imgUnLockCpb, isVisible)
        setVisibility(mViewContentBinding.tvUnLockHint, isVisible)
    }

    @SuppressLint("ClickableViewAccessibility")
    fun addImgCloseLongClickListener() {
        // 添加imgClose的长按事件监听
        mViewContentBinding.imgClose.setOnLongClickListener {
            // 开始进度条走动
            mViewContentBinding.imgCloseCpb.visibility = View.VISIBLE
            mViewContentBinding.imgCloseCpb.setDurationSeconds(3) // 设置进度条完成时间为3秒
            mViewContentBinding.imgCloseCpb.setOnProgressCompleteListener {

                (mViewModel.seconds < 180).yes {//少于三分钟的运动时长需要弹框警示
                    showAlertDialogTwoBtn(
                        getString(R.string.overview_running_finish),
                        getString(R.string.overview_sports_running),
                        "",
                        getString(R.string.overview_sports_finish_hint),
                        message2 ="",
                        true,
                        object : AlertDialogConfirmBtnListener {
                            override fun onCancelBtnClick() {
                                showDialogLoading()
                                setCusSportStop(getEnumToExType(mType!!), curSportId) {
                                    dismissLoadingDialog()
                                    it.yes {
                                        AizoSDKUtil.mHduSportMonitorTask?.destroy()
                                        AizoSDKUtil.mHduSportMonitorTask = null
                                        AizoSDKUtil.getToDaysHr()
                                        finish()
                                    }
                                }
                            }

                            override fun onConfirmBtnClick() {
                                AizoSDKUtil.isConnect().yes {
                                    showDialogLoading()
                                    AizoSDKUtil.setCusSportResume(getEnumToExType(mType!!), curSportId)
                                }.otherwise {
                                    showToast(getString(R.string.ble_device_disconnect))
                                }
                            }
                        }
                    )
                }.otherwise {
                    // 进度条完成时的操作，例如结束运动
                    if (!AizoSDKUtil.isConnect()) {
                        showToast(getString(R.string.ble_device_disconnect))
                        // 手指抬起或取消时停止进度条
                        mViewContentBinding.imgCloseCpb.stopProgress()
                        setVisibility(mViewContentBinding.imgCloseCpb, false)
                        setVisibility(mViewContentBinding.imgCloseBg, false)
                        setVisibility(mViewContentBinding.tvCloseHint, true)
                        changeCloseBtnUI(false)
                        return@setOnProgressCompleteListener
                    }
                    showDialogLoading()
                    setCusSportStop(getEnumToExType(mType!!), curSportId) {
                        dismissLoadingDialog()
                        it.yes {
                            AizoSDKUtil.mHduSportMonitorTask?.destroy()
                            AizoSDKUtil.mHduSportMonitorTask = null

                            AizoSDKUtil.getToDaysHr()
                            RouterHelper.navigationPostcard(RouterHub.ROUTER_OVERVIEW_EXERCISE_DETAILS)
                                .withLong(KeyBundle.BUNDLE_KEY, curSportId)
                                .navigation()
                            finish()
                        }
                    }
                }

            }
            setVisibility(mViewContentBinding.imgCloseCpb, true)
            setVisibility(mViewContentBinding.imgCloseBg, true)
            setVisibility(mViewContentBinding.tvCloseHint, false)
            mViewContentBinding.imgCloseCpb.startProgress()
            true // 返回true表示消费了长按事件
        }

        // 添加imgClose的触摸事件监听，用于检测长按结束
        mViewContentBinding.imgClose.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 手指抬起或取消时停止进度条
                    mViewContentBinding.imgCloseCpb.stopProgress()
                    setVisibility(mViewContentBinding.imgCloseCpb, false)
                    setVisibility(mViewContentBinding.imgCloseBg, false)
                    setVisibility(mViewContentBinding.tvCloseHint, true)
                }
            }
            false // 返回false以不拦截点击事件
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    fun addImgUnLockLongClickListener() {
        // 添加imgClose的长按事件监听
        mViewContentBinding.imgUnLock.setOnLongClickListener {
            // 开始进度条走动
            mViewContentBinding.imgUnLockCpb.visibility = View.VISIBLE
            mViewContentBinding.imgUnLockCpb.setDurationSeconds(3) // 设置进度条完成时间为3秒
            mViewContentBinding.imgUnLockCpb.setOnProgressCompleteListener {
                // 进度条完成时的操作，例如结束运动
                mViewContentBinding.imgUnLockCpb.stopProgress()
                changeUnLockBtnUI(false)
                changePauseBtnUI(true)
            }
            changeUnLockBtnUI(true)
            mViewContentBinding.imgUnLockCpb.startProgress()
            true // 返回true表示消费了长按事件
        }

        // 添加imgClose的触摸事件监听，用于检测长按结束
        mViewContentBinding.imgUnLock.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    mViewContentBinding.imgUnLockCpb.isRunning.yes {
                        // 手指抬起或取消时停止进度条
                        mViewContentBinding.imgUnLockCpb.stopProgress()
                        changePauseBtnUI(false)
                        changeUnLockBtnUI(true)
                    }
                }
            }
            false // 返回false以不拦截点击事件
        }
    }

    override fun onBackPressedSupport() {
    }

//    override fun onTwoButtonCancelClick() {
//        super.onTwoButtonCancelClick()
//        if (!AizoSDKUtil.isConnect()) {
//            showToast(getString(R.string.ble_device_disconnect))
//            return
//        }
//        showDialogLoading()
//        setCusSportStop(getEnumToExType(mType!!),curSportId){
//            dismissLoadingDialog()
//            it.yes {
//                AizoSDKUtil.getToDaysHr()
//                finish()
//            }
//        }
//    }

    override fun onTwoButtonOKClick() {
        super.onTwoButtonOKClick()

        if (!AizoSDKUtil.isConnect()) {
            showToast(getString(R.string.ble_device_disconnect))
            return
        }
    }

    override fun sportStart(result: Boolean, sportId: Long, ringFirm: String) {
        dismissLoadingDialog()
        Log.e("$TAG-sportStart", "YQ: SSSSSS: sportStart ${result}-------${sportId}")
        result.yes {
            TimerUtils.removeTimer(KeyEvents.KEY_TIME_EVENT_DURING_EX)
            TimerUtils.addTimerKey(KeyEvents.KEY_TIME_EVENT_DURING_EX)

            curSportId = sportId
            mViewModel.startTimer()
            changePauseBtnUI(true)
        }.otherwise {
            showAlertDialogTwoBtn(
                getString(R.string.cancel_btn_zh),
                getString(R.string.ok_btn_zh2),
                "提示",
                getString(R.string.overview_failure_tart_movement_hint),
                message2 ="",
                true,
                object : AlertDialogConfirmBtnListener {
                    override fun onCancelBtnClick() {
                        finish()
                    }

                    override fun onConfirmBtnClick() {
                        startSport()
                    }
                }
            )
        }
    }

    override fun sportPause(result: Boolean) {
        dismissLoadingDialog()
        result.yes {
            mViewModel.pauseTimer()
            changePauseBtnUI(false)
            changeCloseBtnUI(true)
            dismissLoadingDialog()
        }.otherwise {
            showToast("暂停运动失败，请重试！")
        }
    }

    override fun sportResume(result: Boolean) {
        mViewModel.resumeTimer()
        changeCloseBtnUI(false)
        changePauseBtnUI(true)
        dismissLoadingDialog()
    }

    override fun sportStop(result: Boolean) {
    }

    override fun sportInfo(
        type: Int,
        timestamp: Long,
        step: Int,
        distance: Int,
        cal: Int,
        cursleeptime: Int,
        totalrunningtime: Int,
        teptime: Int
    ) {
    }
}